import sys
import logging
import datetime
import sys

from fastapi import FastAPI, Response, status, __version__ as fastapi_version
from fastapi.staticfiles import StaticFiles
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
import uvicorn

from src.config import config
from src.constants import (
    APP_NAME, APP_VERSION, APP_DESCRIPTION, 
    API_V1_PREFIX
)
from src.cores.exceptions import (
    CustomException, custom_exception_handler,
    http_exception_handler, validation_exception_handler,
    general_exception_handler
)
from src.cores.database import init_database_with_app
from src.cores.redis import init_redis_with_app, close_redis_with_app
from src.middlewares.cors import add_cors_middleware
from src.middlewares.logging import RequestLoggingMiddleware
from src.utils.logger import setup_logger

# 设置日志
logger = setup_logger(APP_NAME, "logs/app.log")

# 初始化 FastAPI 应用实例
app = FastAPI(
    title=APP_NAME,
    version=APP_VERSION,
    description=APP_DESCRIPTION,
    debug=config.DEBUG_MODE,
    docs_url="/docs" if config.DEBUG_MODE else None,
    redoc_url="/redoc" if config.DEBUG_MODE else None,
)

# 添加中间件
add_cors_middleware(app)
app.add_middleware(RequestLoggingMiddleware, log_level="INFO")

# 添加异常处理器
app.add_exception_handler(CustomException, custom_exception_handler)
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(Exception, general_exception_handler)

# 初始化数据库 (模板项目暂时注释)
# init_database_with_app(app)

# 应用启动事件
@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化操作"""
    logger.info("应用启动中...")
    
    # 初始化数据库连接
    try:
        from src.cores.database import db_manager
        await db_manager.init_database()
        logger.info(f"数据库连接成功: {db_manager.get_database_url().split('@')[1]}")
    except Exception as e:
        logger.error(f"数据库连接失败: {e}")
        # 根据需要决定是否继续启动应用
        # raise e  # 如果数据库是必需的，取消注释这行
    
    try:
        # 初始化Redis连接
        await init_redis_with_app()
        logger.info("Redis初始化完成")
    except Exception as e:
        logger.error(f"Redis初始化失败: {e}")
        # 根据需要决定是否继续启动应用
        # raise e  # 如果Redis是必需的，取消注释这行
    
    logger.info("应用启动完成")

# 应用关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时的清理操作"""
    logger.info("应用关闭中...")
    
    # 关闭数据库连接
    try:
        from src.cores.database import db_manager
        await db_manager.close_database()
        logger.info("数据库连接已关闭")
    except Exception as e:
        logger.error(f"数据库关闭失败: {e}")
    
    try:
        # 关闭Redis连接
        await close_redis_with_app()
        logger.info("Redis连接已关闭")
    except Exception as e:
        logger.error(f"Redis关闭失败: {e}")
    
    logger.info("应用关闭完成")

# 挂载静态文件
app.mount(
    config.STATIC_URL,
    StaticFiles(directory=config.STATIC_DIR),
    name=config.STATIC_NAME,
)


@app.get("/")
async def root() -> dict[str, str]:
    return {"msg": "Hello"}


# 健康检查接口
@app.get("/health")
async def health_check():
    """健康检查接口
    
    用于监控和负载均衡器检查服务状态
    """
    return {
        "status": "ok",
        "timestamp": datetime.datetime.now().isoformat(),
        "environment": "production" if not config.DEBUG_MODE else "development",
        "versions": {
            "app": APP_VERSION,
            "fastapi": fastapi_version,
        }
    }


# API V1 路由
from fastapi import APIRouter

# 创建 V1 API 路由器
api_v1_router = APIRouter()


# 挂载 V1 API 路由
app.include_router(api_v1_router, prefix=API_V1_PREFIX)


if __name__ == "__main__":
    uvicorn.run("main:app", host=config.APP_HOST, port=config.APP_PORT, reload=True)
